package com.csaba.connector.otp.parser;

import java.io.IOException;
import java.io.Reader;
import java.text.ParseException;

import au.id.jericho.lib.html.Element;
import au.id.jericho.lib.html.Source;

public class LoginParser
{
	//private final static Logger logger = LoggerHelper.getDefaultLogger();

	private static final String INDICATOR_ERROR = "hiba";

	//Error patterns:
	//errors on the page: (table areas, td hasab_23 , this is the only <h2/> element on the page.
	// - invalid input: <h2 align="left" style="color: #a80927;">Hiba a bevitt adatokban!</h2>
	//		<p align="justify" class="utolso">Sajnáljuk, de az Ön által megadott számlaszám formátuma hibás.</p>
	// - blocked account: <h2 align="left" style="color: #a80927;">Letiltva!</h2>
	//		<p align="justify">Az Ön Azonosítója felfüggesztésre került. </p>

	public static String parseLoginError( final Reader reader ) throws IOException, ParseException
	{
		final Source source = new Source(reader);

		final StringBuilder message = new StringBuilder();
		// find the account table
		final Element h2 = source.findNextElement(0, "h2");
		if ( h2 != null )
		{
			message.append(h2.getContent().toString());

			final Element p = source.findNextElement(h2.getEnd(), "p");
			if ( p != null )
			{
				message.append(" ");
				message.append(p.getContent().toString());
			}
		}

		if ( message.length() == 0 )
		{
			message.append("Unable to parse error message.");
		}

		return message.toString();
	}

	public static boolean isErrorOccured( final String result )
	{
		return result.contains(INDICATOR_ERROR);
	}
}
